package com.zj.juc.study.future;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @author j
 * @version 1.0.0
 * @ClassName FutureSample
 * @Description FutureTask 与线程池结合
 * @createTime 2024年12月21日 14:03
 */
public class FutureSample {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        //运用FutureTask 和 线程池运行多任务
        long start = System.currentTimeMillis();
        FutureTask<String> task1 = new FutureTask<String>(()->{
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "t1";
        });
        executorService.submit(task1);
        FutureTask<String> task2 = new FutureTask<String>(()->{
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "t2";
        });
        executorService.submit(task2);
        FutureTask<String> task3 = new FutureTask<String>(()->{
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "t3";
        });
        executorService.submit(task3);
        executorService.shutdown();
        System.out.println(System.currentTimeMillis()-start+"all cost time");
        //总耗时在48毫秒所有,结论：运用FutureTask与线程池结合能显著地提升程序性能
    }


    private static void m2(){
        //三个任务，开启多个异步任务线程处理，耗时多少
        FutureTask<String> task = new FutureTask<String>(()->{
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "t1";
        });
        Thread thread1 = new Thread(task,"t1");
        thread1.start();
        //多个任务的话每个都得new一下，会造成臃肿，而且new一个对象会造成gc垃圾回收
        //fixed : 线程池
    }

    private static void m1(){
        //三个任务，目前只有一个main线程，请问耗时多少
        long start = System.currentTimeMillis();
        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);
    }
}
